<template>
	 <view class="content" :style="{'padding-top':'calc(' + statusBarHeight+'px' + ')',backgroundImage: 'url('+inviteBgc+')',height:HH+'px',width:WW+'px'}">
		<uni-nav-bar title="邀请好友"  :border="false" left-icon="left" v-if="!backgroundColor" backgroundColor="transparent"  @clickLeft="back" class="nav" :style="{top:'calc(' + statusBarHeight+'px' + '20rpx)',}"> </uni-nav-bar>
		<uni-nav-bar title="邀请好友"  :border="false" left-icon="left" v-else backgroundColor="#fbdfd9"  @clickLeft="back" class="nav" :style="{top:'calc(' + statusBarHeight+'px' + '20rpx)',}"> </uni-nav-bar>
	     
		 <view class="flex_row_center_center">
			 <image src="../../static/images/other/invite_prople.png" mode="widthFix" class="inviteTitle"></image>
		 </view>
		 
		 <view class="invite_num">
			<view class="invite_num_more">
				<view class="invite_num_top">
					 <image src="../../static/images/other/invite_title.png" mode="aspectFit" class="invite_num_image" ></image>
					 <view class="invite_num_title">我的现金收益</view>
				</view>
				<view class="invite_num_bottom flex_row_between_center">
					<view class="flex_column_center_center">
						<view class="number">0</view>
						<view class="number_label">邀请收益（元）</view>
					</view>
					<view class="flex_column_center_center">
						<view class="number">0</view>
						<view class="number_label">邀请人数（人）</view>
					</view>
				</view>
			</view>
			<view class="flex_row_center_center">
				<image :src="qrcodeSrc" mode="aspectFit" class="invite_qrcode"></image>
			</view>
		 </view>
		 <view class="invite_rules">
			 <view class="invite_rules_title">邀请规则</view>
			 <view class="invite_rules_item">1.点击“立即邀请”按钮，分享邀请页面给好友</view>
			 <view class="invite_rules_item">2.邀请码有有效期，过期后需要重新生成。</view>
			 <view class="invite_rules_item">3.若被邀请的手机号在APP内注销过，则重新注册</view>
		 </view>
		 <view class="invite_button">立即邀请</view>
		
	     
	       <view class="canvas">
	           <canvas id="qrcode" canvas-id="qrcode" :style="{width: `${qrcodeSize}px`, height: `${qrcodeSize}px`}"   />
	       </view>
		   <view class="canvas">
		       <canvas id="firstCanvas" canvas-id="firstCanvas" :style="{width: `${WW}px`, height: `${HH}px`}"   />
		   </view>
	    </view>
</template>

<script>
    import uQRCode from '@/utils/uqrcode.js'

	  import {
		mapState,
		mapMutations
	  } from 'vuex'

    export default {
        data() {
            return {
                imgUrl: getApp().globalData.imgUrl,
                HH: getApp().globalData.windowHeight,
                WW: getApp().globalData.screenWidth,
				statusBarHeight:getApp().globalData.statusBarHeight,
                qrcodeSize: 0, // 二维码大小
				qrcodeSrc:'',
                qrcodeText: 'http://image.zlyz.shop:8082/register.html', // 二维码内容,如果是地址前面建议写上http/https
				bgimg: 'https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/paizhibo_zhifuma/invite.png', // 背景图
				inviteTiTle:'https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/paizhibo_zhifuma/invite_title.png',
				posterUrl:'',//海报地址,
				filePath:'',//二维码base64转成本地地址
				posterIsShow:false,
				
				
				inviteBgc:'https://sy-hws-file-oss.oss-cn-beijing.aliyuncs.com/yj/invite_bg.png',
				backgroundColor:false,
            }
        },
        onLoad() {

               setTimeout(()=>{
				   // this.qrcodeText='http://image.zlyz.shop:8082/register.html?code='+this.userInfo.phone
				   this.makeEQ() // 生成二维码
			   },300)
            
        },
        onShow() {
			
        },
		computed: {
			// ...mapState(['hasLogin', 'userInfo', 'userCenterData'])
		},
		onPageScroll(e) {
			// console.log(e);
			if(e.scrollTop>30){
				this.backgroundColor=true
				
			}else{
				this.backgroundColor=false
			}
		},


        methods: {
			back(){
				uni.navigateBack({delta:1})
			},
            // 生成二维码
            makeEQ() {
                // uni.showLoading({ //增加loading等待效果
                // 	mask:true,
                // })
                let that = this
                this.qrcodeSize = that.WW / 2.1 // 二维码大小
                uQRCode.make({
                    canvasId: 'qrcode',
                    text: that.qrcodeText,
                    size: that.qrcodeSize,
                }).then(res => {
                    // console.log('qrcodeSrc', res);
					  that.qrcodeSrc = res
					  // that.base64ToPath(res).then((filePath) => {
							// 	console.log('本地路径:', filePath);
							// 	that.filePath=filePath
							// 	that.uploadImg()
							//   })
						
					
                })
            },
		    // 将base64图片地址转换为本地地址
	       base64ToPath(base64Url) {
		      return new Promise((resolve, reject) => {
		        const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64Url) || [];
		        if (!format) {
		          reject(new Error('图片格式错误'));
		        }
		        const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.${format}`;
		        uni.getFileSystemManager().writeFile({
		          filePath,
		          data: bodyData,
		          encoding: 'base64',
		          success() {
		            resolve(filePath);
		          },
		          fail(error) {
		            reject(error);
		          },
		        });
		      });
		    },
			// 下载图片
			uploadImg(){
				let that=this
				const promise1 = new Promise((resolve, reject) => {
					uni.downloadFile({
						url: that.bgimg, 
						success: function (res) {
							console.log('resres',res);
							resolve(res)
						}
					})
				})
				const promise2 = new Promise((resolve, reject) => {
					uni.downloadFile({
						url: that.inviteTiTle, 
						success: function (res) {
							console.log('inviteTiTle',res);
							resolve(res)
						}
					})
				})
				
				Promise.all([promise1,promise2]).then((values) => {
					console.log('values',values);
                   this.make_canvas(values[0],values[1]); // 绘制海报
				}); 
			},
			

			//绘制海报
			async make_canvas(bgImg,headImg){
				
				let that = this
				let ctx = uni.createCanvasContext('firstCanvas') //绑定画布 
				ctx.setFillStyle('#eee') 	// 海报背景色
				ctx.fillRect(0, 0, that.WW, that.HH) // 海报背景色参数以此：x轴 y轴 宽 高
				
				ctx.drawImage(bgImg.tempFilePath, 0, 0, that.WW, that.HH); //填充进图片 背景
				
				
				
				ctx.drawImage(headImg.tempFilePath, that.WW/6, 30, that.WW/1.5,  that.WW/10); //填充进图片 背景
				
				ctx.setFontSize(12);
				ctx.setFillStyle("#fff")  //设置文字color
				ctx.setTextAlign('center');
				ctx.fillText("文化不分国界，艺术不分优劣，传承不分民族", that.WW/2, 90,);
				
				ctx.setFillStyle('#FFFFFF') // 二维码后面的白色背景
				ctx.fillRect(that.WW/2 - that.WW/2/1.8 , that.HH-that.WW/2-136, that.WW/1.8,  that.WW/1.8) // 二维码后面的白色背景
				ctx.drawImage(that.filePath,that.WW/2 - that.WW/2.1/2 , that.HH-that.WW/2.1-130, that.WW/2.1, that.WW/2.1); //填充进图片 背景
				
				
				ctx.setFontSize(12);
				ctx.setFillStyle("#0b0af1")  //设置文字color
				ctx.setTextAlign('center');
				ctx.fillText("长按识别二维码，一起来happy!!!", that.WW/2, that.HH-80);
				ctx.draw();  //
				setTimeout(()=>{  //不加延迟的话，base64有时候会赋予undefined
				   uni.canvasToTempFilePath({
					   canvasId:'firstCanvas',
					   success: (res) => { 
						   console.log('firstCanvas',res);
						   that.posterUrl=res.tempFilePath
						   	uni.hideLoading();
					   }
				   })
				},300)
			},
			
			saveImage(){
				console.log('长按');
				let that = this
				uni.showModal({
					title:'提示',
					content:"确定保存图片到本地相册?",
					success:function(res){
						if(res.confirm){
							console.log('确定');
							
							uni.downloadFile({
								url:that.posterUrl,
								success(res){
									if (res.statusCode == 200) {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success(res){
												uni.showToast({
													title:'保存成功!',
												})
											},
											fail(err) {
												uni.showToast({
													title:'图片保存失败',
													icon:'none'
												})
											}
										})
									}else{
											uni.showToast({
											  title: '下载失败,请稍后再试',
											  icon: 'none'
											})
									}
								},
								fail(err) {
									uni.showToast({
											    title: '下载失败,请稍后再试',
											    icon: 'none'
											 })
								}
							})
						}else if(res.cancel){
							console.log('用户点击取消');
						}
					}
				
				})
			},
			posterShare(){
				 wx.showShareImageMenu({ //分享给朋友
				        path: this.posterUrl,
				        success: (res) => {
				            console.log("分享成功:", res);
				        },
				        fail: (err) => {
				            console.log("分享取消:", err);
				        },
				    })
			},




        }
    }
</script>

<style lang="scss">
  page{
    background-color: #f2f2f2;
	// padding-bottom: 30rpx;
  }
  .nav{
	  position: fixed;
	  left: 0;
	  width: 750rpx;
	  z-index: 999;
  }

   .content {
        background-size: 100% auto; //背景图片能够显
        background-repeat: no-repeat;
        position: relative;
    }
	.inviteTitle{
		width: 398rpx;
		height: 200rpx;
		margin-top: 108rpx;
	}
	
	.invite_num{
		margin: 194rpx 16rpx 20rpx 16rpx;
		background-color: #ffffff;
		border-radius: 38rpx;
		padding: 14rpx 10rpx 25rpx 10rpx;
		
		.invite_num_more{
			background-color: #fffaf5;
			
			.invite_num_top{
				
				display: flex;
				justify-content: center;
				position: relative;
				
				.invite_num_title{
					color: #84554e;
					position: absolute;
					left: 50%;
					top: 50%;
					transform: translate(-50%,-50%);
					font-weight: bold;
					font-size: 36rpx
				}
				.invite_num_image{
					width: 612rpx;
					height: 50rpx;
					padding: 0 50rpx;
					border-radius: 38rpx 38rpx 0 0;
				}
			}
		
		    .invite_num_bottom{
				margin-top: 40rpx;
				padding: 0 50rpx 30rpx 50rpx;
				
				.number{
					font-size: 40rpx;
					font-weight: bold;
					color: #825349;
				}
				.number_label{
					margin-top: 10rpx;
					font-size: 28rpx;
					color: #e0b6aa;
				}
			}
		}
		
		.invite_qrcode{
			width: 340rpx;
			height: 340rpx;
			margin-top: 32rpx;
		}
		
		
	}
	
	.invite_rules{
		background-color: #fff;
		margin: 10rpx 16rpx;
		padding: 30rpx 16rpx 30rpx 50rpx;
		border-radius: 38rpx;
		
		.invite_rules_title{
			text-align: center;
			font-size:32rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		.invite_rules_item{
			font-size: 28rpx;
			line-height: 40rpx;
		}
	}
	
	
	.invite_button{
		width: 650rpx;
		margin:20rpx 50rpx;
		color: #FFF;
		background-color: #9e4035;
		font-size: 32rpx;
		font-weight: bold;
		padding: 20rpx;
		border-radius: 46rpx;
		text-align: center;
	}
	
	
	
    .canvas {
        position: absolute;
        height: 100vh;
        width: 100%;
        top: 0;
        left: -9999px;
    }

    .eqcode {
        // position: relative;
        padding: 14px;
        background-color: #FFFFFF;
        box-shadow: 0px 4px 7px 2px rgba(0, 0, 255, 0.18), 0px 0px 11px 3px rgba(0, 177, 254, 0.13);
        border-radius: 8px;
        height: 400rpx;
        width: 400rpx;
        margin: 0 auto 0 auto;
		
		image {
		    width: 100%;
		    height: 100%;
		}
    }
	
	
		
		


  
   
    
</style>